﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace GPLib
{
    //A quick wrapper around the BlockInput for it to be used in a using ( new SafeBlock() ) { } statement
    //for automatic disposal.  Can also disable a control, which gives visual feedback to the user that the UI is disabled.
    internal sealed class SafeBlock : IDisposable
    {

        [DllImport( "user32.dll", CharSet = CharSet.Auto )]
        [return: MarshalAs( UnmanagedType.Bool )]
        private static extern bool BlockInput( [MarshalAs( UnmanagedType.Bool ), In] bool fBlockIt );

        private readonly Control _control;

        public SafeBlock()
        {
            BlockInput( true );
        }
        
        public SafeBlock( Control c )
        {
            BlockInput( true );
            _control = c;
            _control.Enabled = false;
        }

        public void Dispose()
        {
            BlockInput( false );
            if ( _control != null )
                _control.Enabled = true;
        }
    }
}
